/**
 * @file commefankui.js
 */
(function () {
    var ua = navigator.userAgent;
    baidu.browser.se360 = (function () {
        return /360se/i.test(ua);
    })();
    baidu.browser.QQ = (function () {
        return /QQBrowser\/(\d+\.\d+)/i.test(ua) ? RegExp['\x241'] : undefined;
    })();
    baidu.browser.TT = (function () {
        return /TencentTraveler (\d+\.\d+)/i.test(ua) ? RegExp['\x241'] : undefined;
    })();
    baidu.browser.sogou = (function () {
        return /SE 2.X /i.test(ua);
    })();
    baidu.browser.theworld = (function () {
        return /theworld/i.test(ua);
    })();
    baidu.browser.baidu = (function () {
        var v = /BIDUBrowser (\d+\.\d+)/i.test(ua) ? RegExp['\x241'] : undefined;
        if (!v) {
            v = /BIDUBrowser\/(\d+\.\d+)/i.test(ua) ? RegExp['\x241'] : undefined;
        }
        return v;
    })();
    if (!baidu.platform.isLinux) {
        baidu.platform.isLinux = (function () {
            return /linux/i.test(ua);
        })();
    }
    if (!baidu.platform.windows) {
        baidu.platform.windows = (function () {
            if (!baidu.platform.isWindows) {
                return undefined;
            }

            if (/nt 6.1/i.test(ua)) {
                return '7';
            }
            if (/nt 6.0/i.test(ua)) {
                return 'Vista';
            }
            if (/nt 5.2/i.test(ua)) {
                return '2003';
            }
            if (/(nt 5.1|Windows XP)/i.test(ua)) {
                return 'XP';
            }
            if (/nt 5.0/i.test(ua)) {
                return '2000';
            }
            if (/nt/i.test(ua)) {
                return 'NT 4.0';
            }
            if (/(.*98.+9x.*|Windows ME)/.test(ua)) {
                return 'Me';
            }
            if (/98/.test(ua)) {
                return '98';
            }
            if (/95/.test(ua)) {
                return '95';
            }
            return 'UNKNOWN';
        })();
    }
})();

function getOS() {
    var sysAry = ['Android', 'Ipad', 'Iphone', 'Macintosh', 'Windows', 'X11', 'Linux'];
    var name = '';
    for (var i = 0, l = sysAry.length; i < l; i ++) {
        name = sysAry[i];
        if (baidu.platform['is' + name]) {
            if (name === 'Windows') {
                name += ' ' + baidu.platform.windows;
            }
            break;
        }
    }
    return name;

}
function getBrowser() {
    var browserAry = ['maxthon', 'se360', 'QQ', 'TencentTraveler', 'sogou', 'theworld', 'baidu', 'chrome'];
    browserAry.push('firefox');
    browserAry.push('ie');
    browserAry.push('safari');
    browserAry.push('opera');
    var name = '';
    for (var i = 0, l = browserAry.length; i < l; i ++) {
        name = browserAry[i];
        var version = baidu.browser[name];
        if (version) {
            if (typeof(version) !== 'boolean') {
                name += ' ' + version;
            }
            break;
        }
    }
    return name;
}

/**
 * 格式化json
 * @param {string} data jsondata
 * @return {*}
 */
function parseJSON(data) {
    if (!data || baidu.type(data) !== 'string') {
        return null;
    }
    data = baidu.string(data).trim();
    if (window.JSON && window.JSON.parse) {
        return window.JSON.parse(data);
    }
    // JSON RegExp
    var rvalidchars = /^[\],:{}\s]*$/;
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g;
    var rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g;
    if (rvalidchars.test(data.replace(rvalidescape, '@').replace(rvalidtokens, ']').replace(rvalidbraces, ''))) {

        return (new Function('return ' + data))();

    }
    throw new Error('Invalid JSON: ' + data);
}

/**
 * 重新加载页面
 * @param {string} url 重新加载的url
 */
function reloadPage(url) {
    var url = url.split('#');
    var anchor = url[1];
    var params = url[0].split('?')[1];

    if (params) {
        params = '&' + params;
        if (params.indexOf('&rdm=') > -1) {
            params = params.replace(/&rdm=(\w+)\b/, '&rdm=' + (+new Date).toString(32));
        } else {
            params += '&rdm=' + (+new Date).toString(32);
        }
        params = params.substr(1);
    } else {
        params = 'rdm=' + (+new Date).toString(32);
    }

    url = url[0].split('?')[0] + '?' + params;
    if (anchor) {
        url = url + '#' + anchor;
    }
    window.location.href = url;
}

var proxy = function (fn, scope, params) {
    return function () {
        fn.apply(scope || window, params);
    };
};

/* globals $Class */

/**
 *
 * @type {*}
 */
var TipTog = $Class.create({
    options: {
        tipId: '',
        eType: 'click',
        togClass: 'on',
        callback: null
    },
    init: function (htOptions) {
        var self = this;
        baidu.object.merge(this.options, htOptions || {}, {overwrite: true});
        var opt = self.options;

        this.tipO = baidu('#' + opt['tipId']);
        this.btnTog = baidu('#btnTog-' +  opt['tipId']);
        this.btnTog.bind(this.eType || 'click', function (e) {
            e.preventDefault();
            self.toggle();
        });
    },

    toggle: function () {
        var opt = this.options;
        this.tipO.toggleClass(opt['togClass']);
        this.btnTog.toggleClass(opt['togClass']);
    }
});

/**
 * 弹层类
 * @type Popup
 */
var Popup = {
    overlay: undefined,
    dialog: undefined,
    options: {
        // alert | confirm | html  | iframe
        type: 'html',
        content: '',
        title: '提示',
        width: 400,
        height: 300,
        element: null,
        // 是否显示遮罩层
        overlay: true,
        confirmOk: function () {},
        confirmNo: function () {},
        onClose: function () {},
        // alert是否为成功的信息
        alertOk: true,
        // 内容信息title（如：提交成功！）
        contentMsg: '',
        // 对内容的描述信息（如：我们已到您的投诉，请耐心等待）
        contentInfo: ''
    },
    init: function (htOptions) {
        var self = this;
        baidu.object.merge(this.options, htOptions || {}, {overwrite: true});
        var opt = this.options;
        this._generateDialog();
        switch (opt['type']) {
            case 'alert':
                this.alert();
                break;
            case 'confirm':
                this.confirm();
                break;
            case 'html':
                this.fillHtml();
                break;
            case 'iframe':
                this.fillIframe();
                break;
            default:

        }

        baidu(window).bind('resize', function () {
            self.resize();
        });

    },

    _generateDialog: function () {
        var opt = this.options;
        var htm = [];
        if (!this.dialog) {
            htm.push('<div class="pop-diag" id="popupDialog" style="display:none;"><div class="pop-diag-in">');
            var html = '<div class="pop-tit" id="popupTitle">';
            html += '<span class="pop-ico-close" onclick="Popup.hide();">关闭</span>';
            html += opt.title + '</div>';
            htm.push(html);
            htm.push('<div class="pop-body" id="popupBody"></div>');
            htm.push('</div></div>');

            baidu.dom(document.body).append(htm.join(''));

            this.dialog = baidu('#popupDialog');
            this.dialogTit = baidu('#popupTitle');
            this.dialogBody = baidu('#popupBody');
        }
        if (opt.overlay && (!this.overlay)) {
            htm.push('<div class="pop-overlay" id="popupMask" style="display:none;"></div>');
            baidu.dom(document.body).append(htm.join(''));
            this.overlay = baidu('#popupMask');
            this.overlay.click(function () {
                Popup.hide();
            });
        }
    },
    _setDialogCnt: function (html) {
        this.dialogBody.html(html);
        this.show();
        this._setSize();
        this._setPosition();

    },
    _setSize: function () {
        var opt = this.options;
        var dialog = this.dialog;
        var tit = this.dialogTit;
        var diagBody = this.dialogBody;
        // var overlay = this.overlay;
        var pTop = diagBody.css('paddingTop').replace('px', '') * 1;
        var pBottom = diagBody.css('paddingBottom').replace('px', '') * 1;
        var bodyH = opt.height - tit.outerHeight() - pTop - pBottom;
        var pLeft = diagBody.css('paddingLeft').replace('px', '') * 1;
        var pRight = diagBody.css('paddingRight').replace('px', '') * 1;
        var bodyW = opt.width - pLeft - pRight;
        dialog.width(opt.width).height(opt.height);
        diagBody.width(bodyW).height(bodyH);
    },
    resize: function (w, h) {
        if (w) {
            this.options.width = w;
        }
        if (h) {
            this.options.height = h;
        }
        this._setSize();
    },
    addSize: function (w, h) {
        if (w) {
            this.options.width += w;
        }
        if (h) {
            this.options.height += h;
        }
        this._setSize();
    },
    setPosition: function () {
        this._setPosition();
    },
    _setPosition: function () {
        if (this.overlay) {
            this.overlay.width('100%');
            /* globals body */
            var bodySize = body();
            this.overlay.height(Math.max(bodySize.documentHeight, bodySize.viewHeight));
            baidu('body').css({
                overflow: 'hidden'
            });
            if (baidu.browser.ie !== 6) { // IE6下允许出现滚动条，因为dialog的位置不能固定
                baidu('html').css({
                    overflow: 'hidden'
                });
            }
        }
        var opt = this.options;
        var dialog = this.dialog;
        dialog.css('marginTop', -1 * (opt.height / 2 - 1));
        dialog.css('marginLeft', -1 * (opt.width / 2 - 1));

        if (baidu.browser.ie === 6 && opt.element !== null && opt.element !== undefined) {
            dialog.css({
                top: opt.element.offset().top
            });
        }
    },

    alert: function () {
        var opt = this.options;
        var htm = [];
        if (opt['contentMsg']) {
            var titClass = opt['alertOk'] ? 'msgOk' : (opt['alertOk'] === false ? 'msgErr' : '');
            var html = '<div class="pop-cnt-cit">';
            html += '<strong' + (titClass ? (' class="' + titClass + '"') : '') + '>';
            html += opt['contentMsg'] + '</strong></div>';
            htm.push(html);
            if (opt['contentInfo']) {
                htm.push('<div class="popup-cnt">' + opt['contentInfo'] + '</div>');
            }
        } else {
            htm.push('<div class="pop-cnt-tit"><strong>' + opt.content + '</strong></div>');
        }
        var html = '<div class="popup-btn-area">';
        html += '<input type="button" value="确认" class="popupBtn" onclick="Popup.hide();"/></div>';
        htm.push(html);
        this._setDialogCnt(htm.join(''));
    },
    confirm: function () {
        var opt = this.options;
        var htm = [];
        if (opt['contentMsg']) {
            htm.push('<div class="pop-cnt-tit">' + opt['contentMsg'] + '</div>');
            if (opt['contentInfo']) {
                htm.push('<div class="popup-cnt">' + opt['contentInfo'] + '</div>');
            }
        } else {
            htm.push('<div class="pop-cnt-cit"><strong>' + opt.content + '</strong></div>');
        }
        htm.push('<div class="popup-btn-area"><input type="button" value="确认" class="popup-btn" id="popBtnCfmOk"/>');
        htm.push('<input type="button" value="取消" class="popup-btn" id="popBtnCfmNo" /></div>');
        /* globals _setDialogCnt */
        _setDialogCnt(htm.join(''));
        var cfmOk = opt['confirmOk'];
        var cfmNo =  opt['confirmNo'];
        baidu('#popBtnCfmOk').click(function () {
            Popup.onclose();
            if (cfmOk) {
                cfmOk();
            }
        });
        baidu('#popBtnCfmNo').click(function () {
            Popup.onclose();
            if (cfmNo) {
                cfmNo();
            }
        });
    },
    fillHtml: function () {
        var opt = this.options;
        this._setDialogCnt(opt.content);
    },
    fillIframe: function () {
        var opt = this.options;
        var htm = '<iframe frameborder="0" src="' + opt.content + '"></iframe>';
        this._setDialogCnt(htm);
    },
    hide: function () {
        var opt = this.options;
        if (opt.overlay) {
            this.overlay.hide();
            baidu('body').css({
                overflow: 'auto'
            });
            baidu('html').css({
                overflow: 'auto'
            });
        }
        this.dialog.hide();
        if (opt.onClose) {
            opt.onClose();
        }
    },
    show: function () {
        var opt = this.options;
        if (opt.overlay) {
            this.overlay.show();
        }
        this.dialog.show();
    }
};

/**
 * 验证变量
 * @type
 */
var vaildForm = {
    vaild: {
        email: /^[\w\.\-]+@([\w\-]+\.)+[a-z]{2,4}$/i,
        phone: /^\d{7,14}$/,
        domain: /(t1|passport|hiphotos)\.baidu\.com/i,
        http: /^(http:\/\/)/,
        url: /^(\w+\.)+\w{2,4}/,
        comUrl: /^((http:\/\/)(\w+\.)+\w{2,4})|((\w+\.)+\w{2,4})/,
        time: /^(\d{2}|\d{4})[-\/\.年]{1}\d{1,2}[-\/\.月]{1}\d{1,2}(日)?(( \d{1,2}\:\d{1,2})|( \d{1,2}\:\d{1,2}\:\d{1,2}))?$/,
        ip: /^(([01]?[\d]{1,2})|(2[0-4][\d])|(25[0-5]))(\.(([01]?[\d]{1,2})|(2[0-4][\d])|(25[0-5]))){3}$/,
        number: /^\d+$/
    },
    msg: {
        emailEmpty: '请输入邮箱',
        emailErr: '邮箱格式有误',
        urlEmpty: '请输入域名',
        urlErr: '域名格式有误',
        httpErr: '链接地址前需要有http://',
        contentEmpty: '请输入描述',
        contentLong: '您输入的描述内容超过500个汉字，请删减部分描述文字',
        titleEmpty: '请输入标题',
        titleLong: '标题不能超过50个汉字',
        linkEmpty: '请输入投诉链接',
        linkExist: '您已添加该链接',
        linkRepeat: '此链接已被投诉过，请重新输入',
        idErr: 'ID仅包含汉字、数字、字母和下划线',
        idEmpty: '请输入ID',
        idExist: '您已添加该ID',
        idLong: '您输入的ID不能超过7个汉字，请重试',
        ipEmpty: '请输入IP地址',
        ipErr: '您输入的不是IP地址，请重新输入',
        phoneEmpty: '请输入电话',
        phoneErr: '电话内容不正确',
        typeEmpty: '请选择问题类型',
        timeErr: '您输入日期格式有误',
        contactEmpty: '请填写联系方式',
        ok: '<img src="/resources/images/fk/right.png" />'
    },
    formartErrMsg: function (errMsg) {
        var errHtml = '<span class="span-img">'
        + '<img src="/resources/images/fk/form_ques.png" ／>'
        + '</span>'
        + '<span class="span-err">'
        + errMsg
        + '</span>'
        + '<div class="clear"></div>';
        return errHtml;
    },
    isEmpty: function (ipt) {
        var str = baidu.string(typeof (ipt) === 'string' ? ipt : ipt.value).trim();
        return str.length === 0;
    },
    http: function (ipt) {
        var t = this;
        var reg = t.vaild.http;
        var str = baidu.string(typeof (ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    url: function (ipt) {
        var t = this;
        var reg = t.vaild.url;
        var str = baidu.string(typeof (ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    comUrl: function (ipt) {
        var t = this;
        var reg = t.vaild.comUrl;
        var str = baidu.string(typeof (ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    email: function (ipt) {
        var t = this;
        var reg = t.vaild.email;
        var str = baidu.string(typeof (ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    len: function (obj, minLen, maxLen) {
        var t = this;
        var str = baidu.string(typeof (obj) === 'string' ? obj : obj.value).trim();

        if (typeof (obj) !== 'string') {
            var dObj = baidu(obj);
            if (!minLen) {
                if (typeof (dObj.attr('minlength')) === 'undefined') {
                    minLen = 0;
                } else {
                    minLen = dObj.attr('minlength') * 1;
                }
            }
            if (!maxLen) {
                maxLen = dObj.attr('maxlength') * 1;
            }
        }
        // 解决ie8以下\n的问题;
        str = str.replace(/\r\n/g, '');
        str = str.replace(/\n/g, '');
        var byteLen = baidu.string(str).getByteLength();
        var result = (byteLen >= minLen) && (byteLen <= maxLen);
        return result;
    },
    phone: function (ipt) {
        var t = this;
        var reg = t.vaild.phone;
        var str = baidu.string(typeof(ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    ip: function (ipt) {
        var t = this;
        var reg = t.vaild.ip;
        var str = baidu.string(typeof(ipt) === 'string' ? ipt : ipt.value).trim();
        var rlt = reg.test(str);
        if (!rlt) {
            if (str.match(/:/g) && str.match(/:/g).length <= 7 && /::/.test(str)) {
                if (/^([\da-f]{1,4}(:|::)) {1,6}[\da-f]{1,4}$/i.test(str)) {
                    rlt = true;
                }
            } else {
                if (/^([\da-f]{1,4}:) {7}[\da-f]{1,4}$/i.test(str)) {
                    rlt = true;
                }
            }
        }
        return rlt;
    },
    number: function (ipt) {
        var t = this;
        var reg = t.vaild.number;
        var str = baidu.string(typeof(ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },

    // 检查id合法性
    // id格式:汉字字母数字下划线
    validId: function (ipt) {
        var str = baidu.string(typeof(ipt) === 'string' ? ipt : ipt.value).trim();
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) < 127 && !str.substr(i, 1).match(/^\w+$/ig)) {
                return false;
            }
        }
        return true;
    },
    time: function (ipt) {
        var t = this;
        var reg = t.vaild.time;
        var str = baidu.string(typeof(ipt) === 'string' ? ipt : ipt.value).trim();
        return reg.test(str);
    },
    // 设置控件的msg
    setChkMsg: function (ipt, errMsg, okMsg) {
        var id = (typeof(ipt) === 'string') ? ipt : ipt.getAttribute('id');
        var errO = baidu('#' + id + '_err');
        var okO = baidu('#' + id + '_ok');
        if (okMsg === undefined) {
            okMsg = vaildForm.msg.ok;
        }
        if (errMsg === '') {
            errO.html(errMsg).hide();
            okO.html('').hide();
        } else if (errMsg) {
            errO.html(vaildForm.formartErrMsg(errMsg)).show();
            okO.html('').hide();
        } else {
            errO.html('').hide();
            okO = okO[0] ? okO : errO;
            okO.html(okMsg).show();
        }
    }
};

baidu.dom.extend({
    isRequired: function () {
        var required;
        // 修正某些IE7浏览器下required获取始终null的bug
        if (baidu.browser.ie === '7') {
            var outer = this[0].outerHTML;
            var part = outer.slice(0, outer.search(/\/?['"]?>(?![^<]*<['"])/));
            return /\srequired\b/i.test(part) ? 'required' : undefined;
        } else {
            required = this.attr('required');
            if (required === undefined || required === false) {
                return undefined;
            }
            return 'required';
        }
    },
    vaildForm : function (config) {
        var form = this;

        var conFields = config.fields;
        var check = function (obj, cfg, hid, emt) {
            var val = obj.val();
            var okMsg = '';
            if (cfg['okMsg']) {
                okMsg = cfg['okMsg'];
            }
            var regExp = cfg.regExp;
            var result = true;
            var errMsg = null;
            var fieldIsEmpty = vaildForm.isEmpty(val) || cfg['placeholder'] === baidu.string(val).trim();
            if (fieldIsEmpty) {
                if (cfg['placeholder']) {
                    obj.val(cfg['placeholder']);
                }
                if (cfg['required'] || obj.isRequired()) {
                    errMsg = emt !== undefined ? emt : cfg.emptyMsg;
                    result = null;
                } else {
                    errMsg = '';
                }
            } else if (hid === undefined && regExp !== 'isEmpty') {
                var regType = baidu.type(regExp);
                if (regType === 'string') {
                    if (regExp !== 'len' && cfg['longMsg'] && (!vaildForm.len(obj[0]))) {
                        errMsg = cfg['longMsg'];
                        result = false;
                    } else {
                        result = vaildForm[regExp](obj[0]);
                        if (!result) {  errMsg = cfg.errMsg; }
                    }
                } else if (regType === 'regexp') {
                    result = regExp.test(baidu.string(val).trim());
                    if (!result) {
                        errMsg = cfg.errMsg;
                    }
                } else if (regType === 'function') {
                    result = regExp(baidu.string(val).trim());
                    if (!result) {
                        errMsg = cfg.errMsg;
                    }
                }
            }
            vaildForm.setChkMsg(obj.attr('id'), errMsg);

            if (cfg['callback']) {
                result = cfg['callback'](obj[0], result);
            }
            return result;
        };
        if (conFields) {
            for (var k in conFields) {
                var field = form.find(k);
                if (field.attr('type') === 'hidden') {
                    $(k).attr('emptyMsg', conFields[k].emptyMsg);
                    $.fn.hiddenChange = function () {
                        return check(baidu.dom(this), conFields[k], true, baidu.dom(this).attr('emptyMsg'));
                    };
                }
                var placeholder = conFields[k]['placeholder'];
                field.bind(conFields[k]['eType'] || 'blur', (function (key) {
                    return function () {
                        var rlt = check(baidu.dom(this), conFields[key]);
                    };
                })(k));

                if (placeholder) {
                    field.val(placeholder);
                    field.bind('focus', (function (placeholder) {
                        return function () {
                            var val = baidu.string(this.value).trim();
                            if (val === placeholder) {
                                this.value = '';
                            }
                        };
                    })(placeholder));
                }
            }
        }

        if (form.vaildConfig) {
            form.vaildConfig = baidu.object.merge(form.vaildConfig, config, {
                overwrite: true,
                recursive: true
            });
        } else {
            form.vaildConfig = config;
            var submitHandler = function (e) {
                if (config['beforeSubmit']) {
                    config['beforeSubmit']();
                }
                var result = true;
                var fields = form.vaildConfig.fields;

                // 表单中的要提交的数据以json保存
                var fieldJson = {};
                if (fields) {
                    for (var k in fields) {
                        if (fields[k]['noSubmit']) {
                            continue;
                        }

                        var field = form.find(k);
                        if (field) {
                            field.each(function (index, item) {
                                item = baidu.dom(item);
                                var tmpRlt = check(item, fields[k]);
                                var val = item.val();
                                var cfg = fields[k];
                                var fieldIsEmpty = cfg['placeholder'] === baidu.string(val).trim();
                                if (fieldIsEmpty) {
                                    item.val('');
                                }
                                if (tmpRlt) {
                                    fieldJson[item.attr('name')] = item.val();
                                }
                                result = result && tmpRlt;
                            });
                        }
                    }
                }

                if (config['submitCbk']) {
                    // 把检查合法性结果及需要提交的合法的表单数据传给submit回调函数
                    result = config['submitCbk'](result, fieldJson);
                }

                if (!result) {
                    e.preventDefault();
                    return false;
                }

                if (config['afterSubmit']) {
                    window.setTimeout(function () {
                        config['afterSubmit']();
                    }, 0);
                }
            };
            form.submit(submitHandler);
        }
    },
    // 获取或设置验证field的config值
    vaildField: function (fieldId, key, val) {
        var form = this;
        var fieldKey = fieldId.charAt(0) === '#' ? fieldId : ('#' + fieldId);
        var argLen = arguments.length;
        var fieldCfg = form.vaildConfig.fields[fieldKey];
        if (fieldCfg === undefined) {
            return undefined;
        }
        if (argLen === 1) {
            // 获取该field配置json
            return fieldCfg;
        } else if (argLen === 2) {
            // 获取该field配置json中对应key的值
            return fieldCfg[key];
        } else {
            // 设置该field配置json中对应key的值
            fieldCfg[key] = val;
        }
    }
});



baidu.dom(document).ready(function () {
    // userStatus();
//    login.init();

});
